import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';
import { User, UserPreferences } from '@/types';
import { StorageService } from '@/services/storage';

// 用户状态接口
interface UserState {
  // 状态
  user: User | null;
  isAuthenticated: boolean;
  preferences: UserPreferences;
  isLoading: boolean;
  error: string | null;
  
  // 动作
  login: (credentials: LoginCredentials) => Promise<void>;
  logout: () => Promise<void>;
  register: (userData: RegisterData) => Promise<void>;
  updateProfile: (updates: Partial<User>) => Promise<void>;
  updatePreferences: (preferences: Partial<UserPreferences>) => Promise<void>;
  clearError: () => void;
  
  // 初始化
  initialize: () => Promise<void>;
}

// 登录凭证类型
interface LoginCredentials {
  username: string;
  password: string;
}

// 注册数据类型
interface RegisterData {
  username: string;
  email: string;
  password: string;
}

// 默认用户偏好
const defaultPreferences: UserPreferences = {
  defaultColorMode: 'hex',
  theme: 'auto',
  language: 'zh-CN',
  autoSave: true,
  maxHistoryItems: 100,
  showColorNames: true,
  enableAnimations: true
};

/**
 * 用户状态管理 Store
 */
export const useUserStore = create<UserState>()(
  persist(
    (set, get) => ({
      // 初始状态
      user: null,
      isAuthenticated: false,
      preferences: defaultPreferences,
      isLoading: false,
      error: null,

      // 登录
      login: async (credentials: LoginCredentials) => {
        set({ isLoading: true, error: null });
        
        try {
          // 模拟登录验证（实际项目中会调用API）
          if (credentials.username && credentials.password) {
            const user: User = {
              id: 'user_' + Date.now(),
              username: credentials.username,
              email: credentials.username + '@example.com',
              preferences: get().preferences,
              createdAt: new Date(),
              lastLoginAt: new Date()
            };
            
            await StorageService.saveUser(user);
            
            set({ 
              user, 
              isAuthenticated: true, 
              isLoading: false 
            });
          } else {
            throw new Error('用户名和密码不能为空');
          }
        } catch (error) {
          set({ 
            error: error instanceof Error ? error.message : '登录失败', 
            isLoading: false 
          });
          throw error;
        }
      },

      // 注册
      register: async (userData: RegisterData) => {
        set({ isLoading: true, error: null });
        
        try {
          // 验证用户数据
          if (!userData.username || !userData.email || !userData.password) {
            throw new Error('所有字段都是必填的');
          }
          
          const user: User = {
            id: 'user_' + Date.now(),
            username: userData.username,
            email: userData.email,
            preferences: defaultPreferences,
            createdAt: new Date()
          };
          
          await StorageService.saveUser(user);
          
          set({ 
            user, 
            isAuthenticated: true, 
            isLoading: false 
          });
        } catch (error) {
          set({ 
            error: error instanceof Error ? error.message : '注册失败', 
            isLoading: false 
          });
          throw error;
        }
      },

      // 登出
      logout: async () => {
        try {
          set({ 
            user: null, 
            isAuthenticated: false,
            error: null
          });
        } catch (error) {
          console.error('Logout error:', error);
        }
      },

      // 更新用户资料
      updateProfile: async (updates: Partial<User>) => {
        const currentUser = get().user;
        if (!currentUser) {
          throw new Error('用户未登录');
        }

        set({ isLoading: true, error: null });

        try {
          const updatedUser = { 
            ...currentUser, 
            ...updates,
            updatedAt: new Date()
          };
          
          await StorageService.saveUser(updatedUser);
          
          set({ 
            user: updatedUser, 
            isLoading: false 
          });
        } catch (error) {
          set({ 
            error: error instanceof Error ? error.message : '更新资料失败', 
            isLoading: false 
          });
          throw error;
        }
      },

      // 更新用户偏好
      updatePreferences: async (newPreferences: Partial<UserPreferences>) => {
        set({ isLoading: true, error: null });

        try {
          const currentPreferences = get().preferences;
          const updatedPreferences = { 
            ...currentPreferences, 
            ...newPreferences 
          };
          
          await StorageService.savePreferences(updatedPreferences);
          
          const currentUser = get().user;
          if (currentUser) {
            const updatedUser = {
              ...currentUser,
              preferences: updatedPreferences
            };
            await StorageService.saveUser(updatedUser);
            set({ user: updatedUser });
          }
          
          set({ 
            preferences: updatedPreferences, 
            isLoading: false 
          });
        } catch (error) {
          set({ 
            error: error instanceof Error ? error.message : '更新偏好失败', 
            isLoading: false 
          });
          throw error;
        }
      },

      // 清除错误
      clearError: () => {
        set({ error: null });
      },

      // 初始化用户状态
      initialize: async () => {
        set({ isLoading: true });

        try {
          const [user, preferences] = await Promise.all([
            StorageService.getUser(),
            StorageService.getPreferences()
          ]);

          set({
            user,
            isAuthenticated: !!user,
            preferences: preferences || defaultPreferences,
            isLoading: false
          });
        } catch (error) {
          console.error('Failed to initialize user store:', error);
          set({ 
            preferences: defaultPreferences,
            isLoading: false 
          });
        }
      }
    }),
    {
      name: 'user-store',
      storage: createJSONStorage(() => localStorage),
      partialize: (state) => ({
        user: state.user,
        isAuthenticated: state.isAuthenticated,
        preferences: state.preferences
      })
    }
  )
);